<?php

namespace App\Command\ResumeParsing\Service\ParsingSpecial;

use App\Service\FileHandler;
use EchoPHP\Facades\Log;

class ParsingBoss extends ParsingSpecialXml {

    private $defaultAvatar = [];

    function __construct($helper) {
        parent::__construct($helper);
        $this->titleXpath = "//tbl[tr/tc/p/ppr/rpr/sz[@*[local-name()='w:val' and .=28]]]";

        $dir = __DIR__ . '/../Resource/DefaultAvatar/Boss';
        foreach (scandir($dir) as $fileName) {
            if (is_file($dir . '/' . $fileName)) $this->defaultAvatar[$fileName] = file_get_contents($dir . '/' . $fileName);
        }

        $this->get['template'] = function () {
            $this->listXPath("//templateTag[normalize-space()='templateTagName']");    //[contains(., 'templateTagName')][starts-with(normalize-space(), 'templateTagName')]
            $result = $this->xPath->query();
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent);
        };

        $this->get['id'] = $this->tagNotExist;

        $this->get['time'] = $this->tagNotExist;

        $this->get['name'] = function () {
            //$this->listXPath("//tbl[contains(., '|')]/tr/tc[*//sz[@*[local-name()='w:val' and .>'32']]]");
            $result = $this->xPath->query("//tbl[contains(., '|')]/tr/tc[*//sz[@*[local-name()='w:val' and .>'32']]][1]");
            if ($result->length < 1) return '';
            return $this->formatTxt($result[0]->textContent);
        };

        $this->groupGetter['basic'] = array();

        $this->groupGetter['basic'][0] = function () {
            //$this->listXPath("//tbl[contains(., '|')]/tr[*//sz[@*[local-name()='w:val' and .>'32']]][1]/following-sibling::tr[1]");
            $result = $this->xPath->query("//tbl[contains(., '|')]/tr[*//sz[@*[local-name()='w:val' and .>'32']]][1]/following-sibling::tr[1]");
            if ($result->length < 1) return '';
            return preg_split('/\s*\|\s*/u', $this->formatTxt($result[0]->textContent));
        };

        $this->groupGetter['basic'][] = function ($text) {
            if (preg_match('/^\d{2}岁$/u', $text)) {
                return array('age' => $text);
            }
        };

        $this->groupGetter['basic'][] = function ($text) {
            if (preg_match('/^[男女]$/u', $text)) {
                return array('sex' => $text);
            }
        };

        $this->groupGetter['basic'][] = function ($text) {
            static $dictDegree = array(
                "博士后" => 9,
                "博士" => 9,
                "MBA" => 8,
                "EMBA" => 8,
                "硕士" => 7,
                "本科" => 6,
                "大专" => 5,
                "中专" => 4,
                "中技" => 3,
                "中技" => 3,
                "高中" => 2,
                "中学" => 1,
                "初中" => 1,
                "初中以下" => 1,
                "初中及以下" => 1,
                "小学" => 1
            );
            if (isset($dictDegree[$text])) return array('degree' => $text);
        };

        $this->groupGetter['basic'][] = function ($text) {
            $text = $this->formatTxt($text, TRUE);
            if (preg_match('/^(?:\d{1,2}\s*年(?:\s*[01]?\d\s*个?月)?|\d{1,2}\s*个?月)(?:\s*以上|\+)?(?=经验)/u', $text, $matches)) {
                return array('workyear' => $matches[0]);
            }
        };

        $this->get['sex'] = $this->groupGet('sex', 'basic');

        $this->get['nation'] = $this->tagNotExist;

        $this->get['identitycard'] = $this->tagNotExist;

        $this->groupGetter['contact'] = array();

        $this->groupGetter['contact'][0] = function () {
            //$this->listXPath("//tbl[contains(., '|')]/tr[*//sz[@*[local-name()='w:val' and .>'32']]][1]/following-sibling::tr[2]");
            $result = $this->xPath->query("//tbl[contains(., '|')]/tr[*//sz[@*[local-name()='w:val' and .>'32']]][1]/following-sibling::tr[2]");
            if ($result->length < 1) return '';
            return preg_split('/\s*\|\s*/u', $this->formatTxt($result[0]->textContent));
        };

        $this->groupGetter['contact'][] = function ($text) {
            if (preg_match('/^1\d{10}$/', $text)) {
                return array('mobile' => $text);
            }
        };

        $this->groupGetter['contact'][] = function ($text) {
            if (preg_match('/^\S+@[\w\-]+\.\S+$/', $text)) {
                return array('email' => $text);
            }
        };

        $this->get['mobile'] = $this->groupGet('mobile', 'contact');

        $this->get['email'] = $this->groupGet('email', 'contact');

        $this->get['age'] = $this->groupGet('age', 'basic');

        $this->get['married'] = $this->tagNotExist;

        $this->get['politic'] = $this->tagNotExist;

        $this->get['degree'] = $this->groupGet('degree', 'basic');

        $this->groupGetter['expect'] = function () {
            //$this->listXPath("//tbl[normalize-space()='期望职位']/following-sibling::p[1]");
            $result = $this->xPath->query("//tbl[normalize-space()='期望职位']/following-sibling::p[1]");
            if ($result->length < 1) return '';
            if (preg_match('/^(?<position>.+?)\s+(?:(?<expectarea>.+?)\s+)?(?<expectsalary>面议|保密|\d+(?:\.\d+)?\s*[kw万]?\s*元?(?:\s*[-–—~～至到]\s*(?:\d+(?:\.\d+)?\s*[kw万]?)\s*元?)?)(?:以上|以下)?\s+(?<industry>.+?)\s*$/us', $this->formatTxt($result[0]->textContent), $matches)) {
                return array(
                    'position' => $this->formatTxt($matches['position'], TRUE),
                    'expectarea' => $this->formatTxt($matches['expectarea'], TRUE),
                    'expectsalary' => $this->formatTxt($matches['expectsalary'], TRUE),
                    'industry' => $this->formatTxt($matches['industry'], TRUE)
                );
            }
        };

        $this->get['industry'] = $this->groupGet('industry', 'expect');

        $this->get['position'] = $this->groupGet('position', 'expect');

        $this->get['career'] = $this->tagNotExist;

        $this->get['major'] = $this->tagNotExist;

        $this->get['birthday'] = $this->tagNotExist;

        $this->get['workyear'] = $this->groupGet('workyear', 'basic');

        $this->get['workarea'] = $this->tagNotExist;

        $this->get['expectarea'] = $this->groupGet('expectarea', 'expect');

        $this->get['area'] = $this->tagNotExist;

        $this->get['salary'] = $this->tagNotExist;

        $this->get['expectsalary'] = function () {
            $resultText = $this->groupGet('expectsalary', 'expect')();
            $expectsalary = $this->func->parseSalary($resultText);
            if (count($expectsalary)) {
                $this->helper->resumeInfo['expectsalaryfrom'] = $expectsalary['monthly']['begin'];
                $this->helper->resumeInfo['expectsalaryend'] = $expectsalary['monthly']['end'];
                //$this->helper->resumeInfo['expectsalaryafrom'] = $expectsalary['annual']['begin'];
                //$this->helper->resumeInfo['expectsalaryaend'] = $expectsalary['annual']['end'];
            }
            return $resultText;
        };

        $this->get['jobterm'] = $this->tagNotExist;

        $this->get['school'] = $this->tagNotExist;

        $this->get['nofocuse'] = $this->tagNotExist;

        $this->get['workinfo'] = function () {
            $result = $this->getPart('工作经历', true);
            if (!count($result)) return array();
            $data = array();
            $trimCount = 0;
            foreach ($result as $node) {
                if ($node->localName == 'tbl') {
                    if (isset($item)) {
                        $item['comment'] = trim($item['comment']);
                        $data[] = $item;
                    }
                    if (!preg_match('/^(?<company>.+?)\s+(?<duty>.+?)(?:\s*\|\s*(?<department>.+?))?\s*(?<time>(?:(?:19|20)?\d{2}\s*年\s*[01]?\d\s*月(?:\s*[0-3]?\d[日号])?|(?:19|20)?\d{2}\s*(?<delimiter>[\-\.\/\\\\])\s*[01]?\d(?:\k<delimiter>\s*[0-3]?\d)?)(?!\d)(?:(?:\s*[-–—\/\\\\~～到至]\s*)(?<!\d)(?:至今|现在|(?(delimiter)(?:19|20)?\d{2}\s*\k<delimiter>\s*[01]?\d(?:\k<delimiter>\s*[0-3]?\d)?|(?:19|20)?\d{2}\s*年\s*[01]?\d\s*月(?:\s*[0-3]?\d[日号])?))))$/us',
                        $this->formatTxt($node->textContent), $matches)) break;
                    $trimCount = 0;
                    $time = $matches['time'];
                    $tmp = $this->func->parseTimespan($time);
                    $item = array(
                        'comment' => !empty($matches['department']) ? $matches['department'] : '',
                        'time' => $time, 'time_from' => $tmp['begin'], 'time_end' => $tmp['end'],
                        'company' => $matches['company'],
                        'duty' => $matches['duty'],
                    );
                } elseif (isset($item)) {
                    $text = $this->formatTxt($node->textContent);
                    if (!$trimCount) $text = preg_replace('/^内容\s*：\s*/u', '', $text, -1, $trimCount);
                    $item['comment'] .= "\r\n" . $text;
                }
            }
            return $data;
        };

        $this->get['projectinfo'] = $this->tagNotExist;

        $this->get['educationinfo'] = function () {
            $result = $this->getPart('教育经历', true);
            if (!count($result)) return array();
            $data = array();
            foreach ($result as $node) {
                if (!preg_match('/^(?<school>.+?)\s+(?<major>.+?)(?:\s*\|\s*(?<degree>.+?))?\s*(?<time>(?<!\d)(?:(?:19|20)?\d{2}\s*年\s*[01]?\d\s*月(?:\s*[0-3]?\d[日号])?|(?:19|20)?\d{2}(?:\s*(?<delimiter>[\-\.\/\\\\])\s*[01]?\d(?:\k<delimiter>\s*[0-3]?\d)?)?)(?!\d)(?:(?:\s*[-–—\/\\\\~到至]\s*)(?<!\d)(?:至今|现在|(?(delimiter)(?:19|20)?\d{2}\s*\k<delimiter>\s*[01]?\d(?:\k<delimiter>\s*[0-3]?\d)?|(?:19|20)?\d{2}\s*(?:年\s*[01]?\d\s*月(?:\s*[0-3]?\d[日号])?)?))(?!\d))?)$/us',
                    $this->formatTxt($node->textContent), $matches)) break;
                $time = $matches['time'];
                $tmp = $this->func->parseTimespan($time, TRUE);
                $data[] = array(
                    'comment' => '',
                    'time' => $time, 'time_from' => $tmp['begin'], 'time_end' => $tmp['end'],
                    'school' => $matches['school'],
                    'major' => $matches['major'],
                    'degree' => $matches['degree'],
                );
            }
            return $data;
        };

        $this->get['skillinfo'] = $this->tagNotExist;

        $this->get['awardinfo'] = $this->tagNotExist;

        $this->get['commentinfo'] = function () {
            //$this->listXPath("//tbl[normalize-space()='个人优势']/following-sibling::*[self::p or self::tbl]");
            $result = $this->xPath->query("//tbl[normalize-space()='个人优势']/following-sibling::*[self::p or self::tbl]");
            if ($result->length < 1) return '';
            $resultText = '';
            foreach ($result as $node) {
                if ($node->localName == 'tbl') break;
                $resultText .= "\r\n" . $this->formatTxt($node->textContent, TRUE);
            }
            return trim($resultText);
        };

        $this->get['otherinfo'] = function () {
            return trim($this->groupCache['comment']);
        };

        $this->get['avatar'] = function () {
            try {
                //$this->listXPath("//tbl[contains(., '|') and tr/tc[*//sz[@*[local-name()='w:val' and .>'32']]]][1]//pic/blipfill/blip/@*[local-name()='r:embed'][1]");
                if (!count($idNode = $this->xPath->query("//tbl[contains(., '|') and tr/tc[*//sz[@*[local-name()='w:val' and .>'32']]]][1]//pic/blipfill/blip/@*[local-name()='r:embed'][1]"))) return '';
                $imgInfo =& $this->helper->resume['resumeImage'][$idNode[0]->textContent];
                if (in_array($imgInfo['data'], $this->defaultAvatar)) return '';

                return ['data' => &$imgInfo['data'], 'name' => basename($imgInfo['name'])];
            } catch (\Exception $e) {
                Log::error(e_dump($e), ['avatar' => $url ?? ''], 'cmd');
                return '';
            }
        };
    }
}
